package com.hnas.trade.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.hnas.common.util.CommonUtils;
import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.StringUtil;
import com.hnas.trade.dao.AbnormalOrderDao;
import com.hnas.trade.domain.TranState;
import com.hnas.trade.dto.DTORecord;
import com.hnas.trade.orm.AbnormalOrder;

@Component("abnormalOrderDao")
public class AbnormalOrderDaoImpl extends BaseDaoImpl<AbnormalOrder> implements AbnormalOrderDao {

	public AbnormalOrderDaoImpl() {
		super(AbnormalOrder.class);
	}

	@Override
	public AbnormalOrder saveOrUpdate(AbnormalOrder vo) throws Exception {
		AbnormalOrder record = this.entityManager.find(AbnormalOrder.class, vo.getId());
		if (record == null) {
			record = new AbnormalOrder();
			BeanUtils.copyProperties(vo, record);
			record.setId(CommonUtils.getUUID());
			this.entityManager.persist(record);
		} else {
			BeanUtils.copyProperties(record, vo);
			this.entityManager.merge(record);
		}
		return record;
	}

	@Override
	public List<String> findAllAbnormalTranSnoByDate(String startDate, String endDate) {
		String begin = startDate + " 00:00:00";
		String end = endDate + " 23:59:59";
		String sql = "select trade_sno from m_base_wxxnk_abnormal_order where create_time BETWEEN str_to_date('" + begin
				+ "','%Y%m%d %H:%i:%s') AND str_to_date('" + end + "','%Y%m%d %H:%i:%s')";
		Query query = this.entityManager.createNativeQuery(sql);
		return query.getResultList();
	}

	@Override
	public List<AbnormalOrder> findByCondition(String account_id, String order_parent_type, String order_type,
			String date, int pageNo, int pageSize, String trade_status, boolean isToDay) {
		StringBuffer sb = new StringBuffer("from AbnormalOrder t where 1=1 ");
		int j = 1;
		List<Object> paras = new ArrayList<Object>();
		if (StringUtil.isNotEmpty(account_id)) {
			sb.append(" and t.accId = ?" + j++);
			paras.add(account_id);
		}
		if (StringUtil.isNotEmpty(order_parent_type)) {
			sb.append(" and t.orderParentType = ?" + j++);
			paras.add(order_parent_type);
		}

		if (StringUtil.isNotEmpty(order_type)) {
			sb.append(" and t.orderType = ?" + j++);
			paras.add(order_type);
		}

		if (StringUtil.isNotEmpty(trade_status)) {
			sb.append(" and t.tranStatus = ?" + j++);
			paras.add(trade_status);
		}
		if (isToDay) {
			if (StringUtil.isNotEmpty(date)) {
				sb.append(" and str_to_date(t.tradeEndTime,'%Y-%m-%d') = str_to_date(?" + (j++) + ",'%Y-%m-%d')");
				paras.add(date);
			}
		}

		if (StringUtil.isNotEmpty(date)) {
			sb.append(" and str_to_date(t.tradeEndTime,'%Y-%m-%d %H:%i:%s') < str_to_date(?" + (j++)
					+ ",'%Y-%m-%d %H:%i:%s')");
			paras.add(date);
		}
		sb.append(" order by t.tradeEndTime desc");
		Query query = this.entityManager.createQuery(sb.toString());
		for (int i = 1; i < paras.size() + 1; i++) {
			query.setParameter(i, paras.get(i - 1));
		}
		if (!isToDay) {
			query.setFirstResult((pageNo - 1) * pageSize);
			query.setMaxResults(pageSize);
		}
		try {
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<DTORecord> unionFindByCondition(String account_id, String order_parent_type, String order_type,
			String date, String trade_status, Integer pageNo, Integer pageSize, boolean isByDate) {
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		StringBuffer sb1 = new StringBuffer(" where is_deleted=" + true + " ");
		if (StringUtil.isNotEmpty(account_id)) {
			sb.append(" and acc_id='" + account_id + "'");
			sb1.append(" and acc_id='" + account_id + "'");
		}
		if (StringUtil.isNotEmpty(order_parent_type)) {
			sb.append(" and order_parent_type='" + order_parent_type + "'");
			sb1.append(" and order_parent_type='" + order_parent_type + "'");
		}
		if (StringUtil.isNotEmpty(order_type)) {
			sb.append(" and order_type='" + order_type + "'");
			sb1.append(" and order_type='" + order_type + "'");
		}
		if (StringUtil.isNotEmpty(date) && isByDate) {
			sb.append(" and str_to_date(trade_end_time,'%Y-%m-%d') = str_to_date('" + date + "','%Y-%m-%d') ");
			sb1.append(" and str_to_date(trade_end_time,'%Y-%m-%d') = str_to_date('" + date + "','%Y-%m-%d') ");
		}

		sb.append(" and str_to_date(trade_end_time,'%Y-%m-%d %H:%i:%s') < str_to_date('" + date
				+ "','%Y-%m-%d %H:%i:%s')");
		sb1.append(" and str_to_date(trade_end_time,'%Y-%m-%d %H:%i:%s') < str_to_date('" + date
				+ "','%Y-%m-%d %H:%i:%s')");

		if (StringUtil.isNotEmpty(trade_status)) {
			sb.append(" and tran_status in(" + StringUtil.getChangeString(trade_status) + ")");
		}

		String abNormalOrderElements = "id,acc_id,acc_name,after_trade_balance,before_trade_balance,card_no,commidity_id,commidity_name,commidity_type,create_time,creator,is_deleted,mrch_id,mrch_name,mrch_type,need_pay,order_detail,order_no,order_parent_type,order_status,order_type,order_type_name,pay_end_time,payment,psam_id,real_pay,remark,sub_id,swift_number,term_no,trade_end_time,trade_sno,trade_type,update_time,updater,core_trade_sub_type,core_trade_type,is_op_tran,mobile_phone,op_product_id,op_product_type,op_telecom_type,op_tran_status,rech_channel,tran_status,acc_no,activity_id,batch_no,pos_sno,application_type";
		String normalOrderElements = "id,acc_id,acc_name,after_trade_balance,before_trade_balance,card_no,commidity_id,commidity_name,commidity_type,create_time,creator,is_deleted,mrch_id,mrch_name,mrch_type,need_pay,order_detail,order_no,order_parent_type,order_status,order_type,order_type_name,pay_end_time,payment,psam_id,real_pay,remark,sub_id,swift_number,term_no,trade_end_time,trade_sno,trade_type,update_time,updater,core_trade_sub_type,core_trade_type,is_op_tran,mobile_phone,op_product_id,op_product_type,op_telecom_type,op_tran_status,rech_channel,'01' AS tran_status,acc_no,activity_id,batch_no,pos_sno,application_type";
		String sql = "";
		String tran_state = TranState.Normal.getState() + "," + TranState.Rescinded.getState() + ","
				+ TranState.Returned.getState() + "," + TranState.Reversed.getState();
		if (tran_state.equals(trade_status)) {// 查询所有
			sql = "select t.* from (select " + abNormalOrderElements + " from m_base_wxxnk_abnormal_order " + sb
					+ " UNION select " + normalOrderElements + " from m_base_wxxnk_trade_record " + sb1
					+ ") t order by t.trade_end_time desc";
		} else if (TranState.Normal.getState().equals(trade_status)) {// 查询正常
			sql = "select " + normalOrderElements + " from m_base_wxxnk_trade_record " + sb1
					+ " order by trade_end_time desc";
		} else {// 查询异常
			sql = "select " + abNormalOrderElements + " from m_base_wxxnk_abnormal_order " + sb
					+ " order by trade_end_time desc ";
		}
		// 不是当天就分页
		if (!isByDate) {
			if (null != pageNo && null != pageSize) {
				sql += " limit " + pageNo + "," + pageSize;
			}
		}

		Query query = this.entityManager.createNativeQuery(sql, AbnormalOrder.class);
		List<AbnormalOrder> list = query.getResultList();
		List<DTORecord> dtoRecords = null;
		DTORecord dtoRecord = null;
		if (null != list && list.size() > 0) {
			dtoRecords = new ArrayList<DTORecord>();
			for (AbnormalOrder ab : list) {
				dtoRecord = new DTORecord();
				BeanUtils.copyProperties(ab, dtoRecord);
				dtoRecords.add(dtoRecord);
			}
			return dtoRecords;
		}

		return null;
	}

	@Override
	public AbnormalOrder findByTranSno(String tranSno) {
		String hql = "from AbnormalOrder t where t.tradeSno=?1";
		Query query = this.entityManager.createQuery(hql, AbnormalOrder.class);
		query.setParameter(1, tranSno);
		List<AbnormalOrder> list = query.getResultList();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<DTORecord> findTradeRecordList(String account_id, String cardNos, String order_parent_type,
			String order_type, String date, String trade_status, Integer pageNo, Integer pageSize, boolean isByDate) {
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		StringBuffer sb1 = new StringBuffer(" where is_deleted=" + true + " ");
		if (StringUtil.isNotEmpty(account_id)) {
			sb.append(" and acc_id='" + account_id + "'");
			sb1.append(" and acc_id='" + account_id + "'");
		}
		if (StringUtil.isNotEmpty(order_parent_type)) {
			sb.append(" and order_parent_type='" + order_parent_type + "'");
			sb1.append(" and order_parent_type='" + order_parent_type + "'");
		}
		if (StringUtil.isNotEmpty(order_type)) {
			sb.append(" and order_type='" + order_type + "'");
			sb1.append(" and order_type='" + order_type + "'");
		}
		if (StringUtil.isNotEmpty(date) && isByDate) {
			sb.append(" and str_to_date(trade_end_time,'%Y-%m-%d') = str_to_date('" + date + "','%Y-%m-%d') ");
			sb1.append(" and str_to_date(trade_end_time,'%Y-%m-%d') = str_to_date('" + date + "','%Y-%m-%d') ");
		}

		sb.append(" and str_to_date(trade_end_time,'%Y-%m-%d %H:%i:%s') < str_to_date('" + date
				+ "','%Y-%m-%d %H:%i:%s')");
		sb1.append(" and str_to_date(trade_end_time,'%Y-%m-%d %H:%i:%s') < str_to_date('" + date
				+ "','%Y-%m-%d %H:%i:%s')");

		if (StringUtil.isNotEmpty(trade_status)) {
			sb.append(" and tran_status in(" + StringUtil.getChangeString(trade_status) + ")");
		}
		sb.append(" and card_no in(" + StringUtil.getChangeString(cardNos) + ")");
		sb1.append(" and card_no in(" + StringUtil.getChangeString(cardNos) + ")");

		String abNormalOrderElements = "id,acc_id,acc_name,after_trade_balance,before_trade_balance,card_no,commidity_id,commidity_name,commidity_type,create_time,creator,is_deleted,mrch_id,mrch_name,mrch_type,need_pay,order_detail,order_no,order_parent_type,order_status,order_type,order_type_name,pay_end_time,payment,psam_id,real_pay,remark,sub_id,swift_number,term_no,trade_end_time,trade_sno,trade_type,update_time,updater,core_trade_sub_type,core_trade_type,is_op_tran,mobile_phone,op_product_id,op_product_type,op_telecom_type,op_tran_status,rech_channel,tran_status,acc_no,activity_id,batch_no,pos_sno,application_type";
		String normalOrderElements = "id,acc_id,acc_name,after_trade_balance,before_trade_balance,card_no,commidity_id,commidity_name,commidity_type,create_time,creator,is_deleted,mrch_id,mrch_name,mrch_type,need_pay,order_detail,order_no,order_parent_type,order_status,order_type,order_type_name,pay_end_time,payment,psam_id,real_pay,remark,sub_id,swift_number,term_no,trade_end_time,trade_sno,trade_type,update_time,updater,core_trade_sub_type,core_trade_type,is_op_tran,mobile_phone,op_product_id,op_product_type,op_telecom_type,op_tran_status,rech_channel,'01' AS tran_status,acc_no,activity_id,batch_no,pos_sno,application_type";
		String sql = "";
		String tran_state = TranState.Normal.getState() + "," + TranState.Rescinded.getState() + ","
				+ TranState.Returned.getState() + "," + TranState.Reversed.getState();
		if (tran_state.equals(trade_status)) {// 查询所有
			sql = "select t.* from (select " + abNormalOrderElements + " from m_base_wxxnk_abnormal_order " + sb
					+ " UNION select " + normalOrderElements + " from m_base_wxxnk_trade_record " + sb1
					+ ") t order by t.trade_end_time desc";
		} else if (TranState.Normal.getState().equals(trade_status)) {// 查询正常
			sql = "select " + normalOrderElements + " from m_base_wxxnk_trade_record " + sb1
					+ " order by trade_end_time desc";
		} else {// 查询异常
			sql = "select " + abNormalOrderElements + " from m_base_wxxnk_abnormal_order " + sb
					+ " order by trade_end_time desc ";
		}
		// 不是当天就分页
		if (!isByDate) {
			if (null != pageNo && null != pageSize) {
				sql += " limit " + pageNo + "," + pageSize;
			}
		}

		Query query = this.entityManager.createNativeQuery(sql, AbnormalOrder.class);
		List<AbnormalOrder> list = query.getResultList();
		List<DTORecord> dtoRecords = null;
		DTORecord dtoRecord = null;
		if (null != list && list.size() > 0) {
			dtoRecords = new ArrayList<DTORecord>();
			for (AbnormalOrder ab : list) {
				dtoRecord = new DTORecord();
				BeanUtils.copyProperties(ab, dtoRecord);
				dtoRecords.add(dtoRecord);
			}
			return dtoRecords;
		}

		return null;
	}

	@Override
	public List<AbnormalOrder> findAbnormalOrderList(String account_id, String cardNos, String order_parent_type,
			String order_type, String date, int pageNo, int pageSize, String trade_status, boolean isToDay) {
		StringBuffer sb = new StringBuffer("from AbnormalOrder t where 1=1 ");
		int j = 1;
		List<Object> paras = new ArrayList<Object>();
		if (StringUtil.isNotEmpty(account_id)) {
			sb.append(" and t.accId = ?" + j++);
			paras.add(account_id);
		}
		if (StringUtil.isNotEmpty(order_parent_type)) {
			sb.append(" and t.orderParentType = ?" + j++);
			paras.add(order_parent_type);
		}

		if (StringUtil.isNotEmpty(order_type)) {
			sb.append(" and t.orderType = ?" + j++);
			paras.add(order_type);
		}

		if (StringUtil.isNotEmpty(trade_status)) {
			sb.append(" and t.tranStatus = ?" + j++);
			paras.add(trade_status);
		}
		if (isToDay) {
			if (StringUtil.isNotEmpty(date)) {
				sb.append(" and str_to_date(t.tradeEndTime,'%Y-%m-%d') = str_to_date(?" + (j++) + ",'%Y-%m-%d')");
				paras.add(date);
			}
		}

		if (StringUtil.isNotEmpty(date)) {
			sb.append(" and str_to_date(t.tradeEndTime,'%Y-%m-%d %H:%i:%s') < str_to_date(?" + (j++)
					+ ",'%Y-%m-%d %H:%i:%s')");
			paras.add(date);
		}
		sb.append(" and t.cardNo in(" + StringUtil.getChangeString(cardNos) + ")");
		sb.append(" order by t.tradeEndTime desc");
		Query query = this.entityManager.createQuery(sb.toString());
		for (int i = 1; i < paras.size() + 1; i++) {
			query.setParameter(i, paras.get(i - 1));
		}
		if (!isToDay) {
			query.setFirstResult((pageNo - 1) * pageSize);
			query.setMaxResults(pageSize);
		}
		try {
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
